package ae.pcfc.etks.online.web.controller.admin.general.service.register;

/* $Id: AdminRegisterServiceController 
 * Copyright (C) 2011, Trakhees
 *  
 *  History
 *
 * Date  			Author 					Remarks
 * -------------------------------------------------------------
 * April 19, 2011 	Neha_Chauhan 	        Created
 *
 */

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.Locale;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;

import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.support.SessionStatus;
import org.springframework.web.servlet.support.RequestContextUtils;
import org.springframework.web.util.WebUtils;

import ae.pcfc.etks.online.common.ConstantsCommon;
import ae.pcfc.etks.online.common.delegate.ServiceDelegate;
import ae.pcfc.etks.online.common.delegate.UtilityDelegate;
import ae.pcfc.etks.online.common.vo.ClientRoleVO;
import ae.pcfc.etks.online.common.vo.DepartmentVO;
import ae.pcfc.etks.online.common.vo.LabelVO;
import ae.pcfc.etks.online.common.vo.ServiceAttributesVO;
import ae.pcfc.etks.online.common.vo.ServiceVO;
import ae.pcfc.etks.online.web.ConstantsAdmin;
import ae.pcfc.etks.online.web.PageType;
import ae.pcfc.etks.online.web.ViewPath;
import ae.pcfc.etks.online.web.ViewUtils;
import ae.pcfc.etks.online.web.common.Constants;
import ae.pcfc.etks.online.web.controller.BaseController;
import ae.pcfc.etks.online.web.model.Service;

/**
 * Controller that handles all {@link AdminRegisterServiceController}-related
 * requests, i.e.: all requests for /admin/general/service/register/*
 * 
 * @author Neha Chauhan
 */

@Controller
@RequestMapping(ViewPath.ADMIN_REGISTER_SERVICE)
public class AdminRegisterServiceController extends BaseController {

	

	private ServiceDelegate serviceDelegate;

	@Resource(name = "serviceDelegate")
	public void setServiceDelegate(ServiceDelegate serviceDelegate) {
		this.serviceDelegate = serviceDelegate;
	}

	private UtilityDelegate utilityDelegate;

	@Resource(name = "utilityDelegate")
	public void setUtilityDelegate(UtilityDelegate utilityDelegate) {
		this.utilityDelegate = utilityDelegate;
	}

	@ModelAttribute(value = ConstantsAdmin.ADMIN_REGISTER_SERVICE_MODEL_KEY)
	public Service populateServiceInfoEdit(HttpServletRequest request,
			@Valid Service service, BindingResult errors,
			@RequestParam(value = "id", required = false) String id) {

		if (id != null) {
			
			ServiceVO serviceVO = serviceDelegate
					.getServiceByPrimaryKey(new Long(id));
			ServiceAttributesVO attributesVO = new ServiceAttributesVO();
			List<ServiceAttributesVO> arrServiceAttributes;
			// TODO: Mapper has to be used below
			if (serviceVO != null) {
				arrServiceAttributes = new ArrayList<ServiceAttributesVO>();
				service.setStrServiceNameEng(serviceVO.getStrServiceNameEng());
				service.setStrServiceNameArb(serviceVO.getStrServiceNameArb());
				service.setArrServiceRole(serviceVO.getArrServiceRole());
				service.setArrServiceDeptsCode(serviceVO
						.getArrServiceDeptsCode());
				service.setStrNeccessity(serviceVO.getStrNeccessity());
				service.setStrServiceAttributeNameArb(serviceVO
						.getStrServiceAttributeNameArb());
				service.setStrServiceAttributeNameEng(serviceVO
						.getStrServiceAttributeNameEng());
				attributesVO.setStrServiceAttributeNameARB(serviceVO
						.getStrServiceAttributeNameArb());
				attributesVO.setStrServiceAttributeNameENG(serviceVO
						.getStrServiceAttributeNameEng());
				attributesVO.setStrNecessisty(serviceVO.getStrNeccessity());
				arrServiceAttributes.add(attributesVO);
				service.setArrServiceAttributes(arrServiceAttributes);

			}

		}
		return service;

	}

	@ModelAttribute(ConstantsAdmin.ADMIN_SERVICE_ROLES_LIST)
	public List<LabelVO> populateServiceRolesList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();
		LabelVO labelVO;
		List<ClientRoleVO> clientRoleVOs = utilityDelegate.getClientRoleList(
				null, false);
		// TODO: Mapper has to be used below
		for (ClientRoleVO roleVO : clientRoleVOs) {
			labelVO = new LabelVO();
			labelVO.setId(roleVO.getStrCrId());
			labelVO.setLabelAr(roleVO.getStrCrDescArb());
			labelVO.setLabelEn(roleVO.getStrCrDesc());
			labelList.add(labelVO);

		}

		return labelList;
	}

	@ModelAttribute(ConstantsAdmin.ADMIN_SERVICE_OWNER_LIST)
	public List<LabelVO> populateServiceOwnerList() {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();

		// TODO: Mapper has to be used below
		List<DepartmentVO> depVOs = utilityDelegate.getDepartments();
		for (DepartmentVO depVO : depVOs) {
			labelVO = new LabelVO();
			labelVO.setId(depVO.getStrDeptId().toString());
			labelVO.setLabelAr(depVO.getStrDeptCode());
			labelVO.setLabelEn(depVO.getStrDeptCode());
			labelList.add(labelVO);

		}

		/*
		 * labelVO.setId("1"); labelVO.setLabelAr("CED - Ar");
		 * labelVO.setLabelEn("CED"); labelList.add(labelVO);
		 * 
		 * labelVO = new LabelVO(); labelVO.setId("2");
		 * labelVO.setLabelAr("CLS - Ar"); labelVO.setLabelEn("CLS");
		 * labelList.add(labelVO);
		 * 
		 * labelVO = new LabelVO(); labelVO.setId("3");
		 * labelVO.setLabelAr("EHS - Ar"); labelVO.setLabelEn("EHS");
		 * labelList.add(labelVO);
		 */
		return labelList;
	}

	@ModelAttribute(ConstantsAdmin.ADMIN_SERVICE_NECESSITY_LIST)
	public List<LabelVO> populateServiceNecessityList(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		labelVO.setId(ConstantsAdmin.SERVICE_ATTR_MANDATORY);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.attr.mandatory", null, locale));

		labelList.add(labelVO);

		labelVO = new LabelVO();
		labelVO.setId(ConstantsAdmin.SERVICE_ATTR_OPTIONAL);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.attr.optional", null, locale));

		labelList.add(labelVO);

		return labelList;
	}

	@ModelAttribute(ConstantsAdmin.ADMIN_SERVICE_TYPE_LIST)
	public List<LabelVO> populateServiceTypeList(Locale locale) {

		List<LabelVO> labelList = new ArrayList<LabelVO>();

		LabelVO labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.SERVICE_INTERNAL);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.internal", null, locale));

		labelList.add(labelVO);

		labelVO = new LabelVO();
		labelVO.setId(ConstantsCommon.SERVICE_EXTERNAL);
		labelVO.setDisplayLabel(getMessageSource().getMessage(
				"label.service.external", null, locale));

		labelList.add(labelVO);

		return labelList;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * admin/general/service/register/form.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/service/register/form.jsp
	 */

	@RequestMapping(value = "/form.htm", method = RequestMethod.GET)
	public void form(
			@ModelAttribute(value = ConstantsAdmin.ADMIN_REGISTER_SERVICE_MODEL_KEY) Service command) {
		command.setStrServiceType(ConstantsCommon.SERVICE_EXTERNAL);
	}

	/**
	 * Custom handler for displaying the form, i.e.:POST requests for
	 * admin/general/service/register/form.jsp
	 * 
	 * @see #form(Service)
	 * @see WEB-INF/jsp/admin/general/service/register/form.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/form.htm")
	public String form(
			HttpServletRequest request,
			SessionStatus status,
			HttpSession session,
			@ModelAttribute(value = ConstantsAdmin.ADMIN_REGISTER_SERVICE_MODEL_KEY) @Valid Service service,
			BindingResult errors) {

		boolean isAdd = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.ADD_BUTTON);
		boolean isSave = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.SAVE_BUTTON);
		boolean isDelete = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.DELETE_BUTTON);

		String strAttribute = "";

		if (errors.hasErrors()) {

			return ViewUtils.DEFAULT_VIEW;

		}

		else if (isAdd) {

			if (StringUtils.isBlank(service.getStrServiceAttributeNameArb())) {
				String[] messageArgs = new String[] { getMessageSource()
						.getMessage("label.serviceattributes", null,
								RequestContextUtils.getLocale(request)) };
				errors.reject("error.service.attribute.name.arb", messageArgs,
						null);
				return ViewUtils.DEFAULT_VIEW;

			} else if (StringUtils.isBlank(service
					.getStrServiceAttributeNameEng())) {
				String[] messageArgs = new String[] { getMessageSource()
						.getMessage("label.serviceattributes", null,
								RequestContextUtils.getLocale(request)) };
				errors.reject("error.service.attribute.name.eng", messageArgs,
						null);
				return ViewUtils.DEFAULT_VIEW;
			}
			if (service.getArrServiceAttributes() == null)
				service.setArrServiceAttributes(new ArrayList<ServiceAttributesVO>());

			if (service.getArrServiceAttributes() != null
					&& service.getArrServiceAttributes().size() > 0) {
				for (ServiceAttributesVO listVO : service
						.getArrServiceAttributes()) {
					if (listVO.getStrServiceAttributeNameENG()
							.equalsIgnoreCase(
									service.getStrServiceAttributeNameEng())) {
						String[] messageArgs = new String[] { getMessageSource()
								.getMessage("label.serviceattributes", null,
										RequestContextUtils.getLocale(request)) };
						errors.reject("error.repeat", messageArgs, null);
						return ViewUtils.DEFAULT_VIEW;
					}
				}
			}

			ServiceAttributesVO attributesVO = new ServiceAttributesVO();
			this.getMapper().map(service, attributesVO);

			service.getArrServiceAttributes().add(attributesVO);

			String[] messageArgs = new String[] { getMessageSource()
					.getMessage("success.user.info.edit", null,
							RequestContextUtils.getLocale(request)) };

		} else if (isDelete) {
			strAttribute = request.getParameter("row");

			for (int i = 0; i < service.getArrServiceAttributes().size(); i++) {

				String id = (service.getArrServiceAttributes().get(i)
						.getStrServiceAttributeNameENG());

				if (strAttribute.equals(id)) {
					service.getArrServiceAttributes().remove(i);
					break;
				}

			}

		} else if (isSave) {
			// Commented as sevice variable are optional
			/*
			 * if (service.getStrDefaultService() == null ||
			 * !(service.getStrDefaultService().equals("Y"))) { if
			 * (service.getArrServiceAttributes() == null) {
			 * 
			 * String[] messageArgs = new String[] {
			 * getMessageSource().getMessage("label.serviceattributes", null,
			 * RequestContextUtils.getLocale(request)) };
			 * errors.reject("error.service.attribute.null", messageArgs, null);
			 * return ViewUtils.DEFAULT_VIEW; }
			 * 
			 * }
			 */
			if (service != null
					&& service.getArrServiceRole() == null
					&& ConstantsCommon.SERVICE_EXTERNAL
							.equalsIgnoreCase(service.getStrServiceType())) {
				errors.reject("error.service.arrServiceRole");
				return ViewUtils.DEFAULT_VIEW;

			}
			if (ConstantsCommon.SERVICE_INTERNAL.equalsIgnoreCase(service
					.getStrServiceType())) {
				service.setArrServiceAttributes(null);
				service.setStrDefaultService(null);
				service.setArrServiceDeptsCode(null);
				List<Integer> serviceRoles = new ArrayList<Integer>();
				serviceRoles
						.add(Integer
								.valueOf(ConstantsCommon.SERVICE_ROLE_ID_INTERNAL_SERVICE));
				service.setArrServiceRole(serviceRoles);
				service.setStrServiceOwner(ConstantsCommon.DEFAULT_DEPT_CODE_INTERNAL_SERVICE);
			}

			if (!(service.getStrDefaultService() == null))
				service.setArrServiceAttributes(null);

			ServiceVO serviceVO = new ServiceVO();
			getMapper().map(service, serviceVO);
			serviceVO.setStrStatus(Constants.ACTIVE);
			serviceVO.setCreateDate(Calendar.getInstance().getTime());
			if (serviceDelegate.serviceRegistration(serviceVO)) {
				status.setComplete();
				;
				service.reset();
				/*
				 * request.setAttribute("success",
				 * getMessageSource().getMessage(
				 * "label.success.registerservice", null,
				 * RequestContextUtils.getLocale(request))); return
				 * ViewUtils.DEFAULT_VIEW;
				 */

				session.setAttribute(
						"success",
						getMessageSource().getMessage(
								"label.success.registerservice", null,
								RequestContextUtils.getLocale(request)));
				return ViewUtils.getRedirect(ViewPath.ADMIN_REGISTER_SERVICE,
						PageType.LIST);
			}

		}

		// status.setComplete();
		return ViewUtils.DEFAULT_VIEW;
	}

	/**
	 * Custom handler for displaying the form, i.e.: GET requests for
	 * admin/general/service/register/edit.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/service/register/edit.jsp
	 */

	@RequestMapping(value = "/edit.htm", method = RequestMethod.GET)
	public void edit(
			@RequestParam(value = "serviceId", required = true) String serviceId,
			@ModelAttribute(value = ConstantsAdmin.ADMIN_REGISTER_SERVICE_MODEL_KEY) Service command) {
		ServiceVO serviceVO = this.serviceDelegate.getServiceByPrimaryKey(Long
				.valueOf(serviceId));
		if (serviceVO != null) {
			this.getMapper().map(serviceVO, command);
		}
	}

	/**
	 * Custom handler for displaying the form, i.e.: POST requests for
	 * admin/general/service/register/edit.jsp
	 * 
	 * @see WEB-INF/jsp/admin/general/service/register/edit.jsp
	 */

	@RequestMapping(method = RequestMethod.POST, value = "/edit.htm")
	public String edit(
			HttpServletRequest request,
			SessionStatus status,
			HttpSession session,
			@ModelAttribute(value = ConstantsAdmin.ADMIN_REGISTER_SERVICE_MODEL_KEY) @Valid Service service,
			BindingResult errors) {

		boolean isAdd = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.ADD_BUTTON);
		boolean isSave = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.SAVE_BUTTON);
		boolean isDelete = WebUtils.hasSubmitParameter(request,
				ConstantsAdmin.DELETE_BUTTON);

		String index = "";

		if (errors.hasErrors()) {

			return ViewUtils.DEFAULT_VIEW;

		}

		else if (isAdd) {

			if (StringUtils.isBlank(service.getStrServiceAttributeNameArb())) {
				String[] messageArgs = new String[] { getMessageSource()
						.getMessage("label.serviceattributes", null,
								RequestContextUtils.getLocale(request)) };
				errors.reject("error.service.attribute.name.arb", messageArgs,
						null);
				return ViewUtils.DEFAULT_VIEW;

			} else if (StringUtils.isBlank(service
					.getStrServiceAttributeNameEng())) {
				String[] messageArgs = new String[] { getMessageSource()
						.getMessage("label.serviceattributes", null,
								RequestContextUtils.getLocale(request)) };
				errors.reject("error.service.attribute.name.eng", messageArgs,
						null);
				return ViewUtils.DEFAULT_VIEW;
			}
			if (service.getArrServiceAttributes() == null)
				service.setArrServiceAttributes(new ArrayList<ServiceAttributesVO>());

			if (service.getArrServiceAttributes() != null
					&& service.getArrServiceAttributes().size() > 0) {
				for (ServiceAttributesVO listVO : service
						.getArrServiceAttributes()) {
					if (listVO.getStrServiceAttributeNameENG()
							.equalsIgnoreCase(
									service.getStrServiceAttributeNameEng())) {
						String[] messageArgs = new String[] { getMessageSource()
								.getMessage("label.serviceattributes", null,
										RequestContextUtils.getLocale(request)) };
						errors.reject("error.repeat", messageArgs, null);
						return ViewUtils.DEFAULT_VIEW;
					}
				}
			}

			ServiceAttributesVO attributesVO = new ServiceAttributesVO();
			this.getMapper().map(service, attributesVO);
			attributesVO.setServiceAttrStatus(ConstantsCommon.ACTIVE);
			service.getArrServiceAttributes().add(attributesVO);

			String[] messageArgs = new String[] { getMessageSource()
					.getMessage("success.user.info.edit", null,
							RequestContextUtils.getLocale(request)) };

		} else if (isDelete) {
			index = request.getParameter("row");
			ServiceAttributesVO attrVO = service.getArrServiceAttributes().get(
					Integer.parseInt(index));
			if (attrVO != null) {
				attrVO.setServiceAttrStatus(ConstantsCommon.DISABLE);
			}
			/*
			 * for (int i = 0; i < service.getArrServiceAttributes().size();
			 * i++) {
			 * 
			 * String id = (service.getArrServiceAttributes().get(i)
			 * .getStrServiceAttributeNameENG());
			 * 
			 * if (strAttribute.equals(id)) {
			 * service.getArrServiceAttributes().remove(i); break; }
			 * 
			 * } service.getArrServiceAttributes().remove(index);
			 */
		} else if (isSave) {
			// Commented as sevice variable are optional
			/*
			 * if (service.getStrDefaultService() == null ||
			 * !(service.getStrDefaultService().equals("Y"))) { if
			 * (service.getArrServiceAttributes() == null) {
			 * 
			 * String[] messageArgs = new String[] {
			 * getMessageSource().getMessage("label.serviceattributes", null,
			 * RequestContextUtils.getLocale(request)) };
			 * errors.reject("error.service.attribute.null", messageArgs, null);
			 * return ViewUtils.DEFAULT_VIEW; }
			 * 
			 * }
			 */

			if (ConstantsCommon.SERVICE_INTERNAL.equalsIgnoreCase(service
					.getStrServiceType())) {
				service.setArrServiceAttributes(null);
				service.setStrDefaultService(null);
				service.setArrServiceDeptsCode(null);
				List<Integer> serviceRoles = new ArrayList<Integer>();
				serviceRoles
						.add(Integer
								.valueOf(ConstantsCommon.SERVICE_ROLE_ID_INTERNAL_SERVICE));
				service.setArrServiceRole(serviceRoles);
				service.setStrServiceOwner(ConstantsCommon.DEFAULT_DEPT_CODE_INTERNAL_SERVICE);
			}

			if (!(service.getStrDefaultService() == null))
				service.setArrServiceAttributes(null);

			ServiceVO serviceVO = new ServiceVO();
			getMapper().map(service, serviceVO);
			if (serviceDelegate.serviceUpdate(serviceVO)) {
				status.setComplete();
				;
				service.reset();
				/*
				 * request.setAttribute("success",
				 * getMessageSource().getMessage(
				 * "label.success.registerservice", null,
				 * RequestContextUtils.getLocale(request))); return
				 * ViewUtils.getForward(ViewPath.ADMIN_REGISTER_SERVICE,
				 * PageType.LIST);
				 */

				session.setAttribute(
						"success",
						getMessageSource().getMessage(
								"label.success.registerservice", null,
								RequestContextUtils.getLocale(request)));
				return ViewUtils.getRedirect(ViewPath.ADMIN_REGISTER_SERVICE,
						PageType.LIST);
			}

		}

		// status.setComplete();
		return ViewUtils.DEFAULT_VIEW;
	}

}
